<template>
  <div class="publish-article">
    <Header />
    <div class="breadcrumb">
      {{ t('blog.actbtn') }}
    </div>

    <el-form
      ref="txtFormEl"
      :model="txtForm"
      :rules="txtRules"
    >
      <div class="g-con-m">
        <div class="user">
          <div class="left">
            <div class="head-sculpture">
              <img
                :src="creatorInfo.avatar || creatorInfo.publishUserAvatar"
                alt=""
              />
            </div>
            <div class="name">
              <h2>{{ creatorInfo.customerName }}</h2>
              <p>{{ creatorInfo.label }}</p>
            </div>
          </div>
          <div class="right">
            <!-- <router-link :to="'/mPublishArticle'">
                    <el-button type="primary">{{ t('blog.actbtn') }}</el-button>
                    </router-link> -->
          </div>
        </div>
        <div class="partition">
          <span>*</span>
          <!-- Publish to partition： -->
          {{ t('organizationStructure.subzone') }}
        </div>
        <el-form-item prop="zoningId">
          <div class="btn-list">
            <el-button
              :class="{ active: txtForm.zoningId == item.id }"
              v-for="(item, index) in zoningList"
              :key="index"
              @click="txtForm.zoningId = item.id"
              >{{ item.zoningName }}</el-button
            >
          </div>
        </el-form-item>
        <div class="mt-2">
          <el-form-item prop="articleTitle">
            <el-input
              style="height: 40px"
              v-model="txtForm.articleTitle"
              :placeholder="t('organizationStructure.Information.p14')"
              :maxlength="100"
              class="input"
            ></el-input>
          </el-form-item>
        </div>
        <el-form-item prop="articleText">
          <el-input
            class="mt-1"
            type="textarea"
            resize="none"
            :autosize="{ minRows: 6, maxRows: 6 }"
            v-model="txtForm.articleText"
            :placeholder="t('organizationStructure.Information.p15')"
            :maxlength="8000"
          ></el-input>
        </el-form-item>
        <div class="mt-1">
          <Uploads
            ref="upload1"
            list-type="picture-card"
            :limit="18"
            @change="setFileList"
          ></Uploads>
        </div>
        <div class="sub-box">
          <el-button
            class="sub-btn mt-2 mb-4"
            @click="addArticle"
          >
            {{ t('organizationStructure.operateType1') }}
          </el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Uploads from '@/components/Uploads.vue'
import { useI18n } from 'vue-i18n'
import Header from '../layout/Header.vue'
import { listPage, popularList, articleLike, articleCancelLike, getCustomerInfo, cancelFavorite, articleCollect, getZoningList, articleAdd, articleReport, getCommentList, getNoticesList } from '@/service/blog.js'
import { uploads } from '@/service/common.js'
import { dateFormat, openUrl } from '@/utils/index'
import bg1 from '@/assets/img/blog_01.png'
import bg2 from '@/assets/img/blog_02.png'
import bg3 from '@/assets/img/blog_03.png'
import bg4 from '@/assets/img/blog_04.png'
import bg5 from '@/assets/img/blog_05.png'
import bg6 from '@/assets/img/blog_06.png'
import useDict from '@/hooks/useDict'
const { dictData, getDictData } = useDict()

import { showSuccessToast, showFailToast } from 'vant'
import 'vant/es/toast/style'

const tabList = ref(null)
const router = useRouter()
const route = useRoute()
const { t, locale } = useI18n()
const reportDialog = ref(false)
const diaologVis = ref(false)
const zoningList = ref([])
const listData = ref([])
const hotListData = ref([])
const creatorInfo = ref({})
const bgImgArr = ref([bg1, bg2, bg3, bg4, bg5, bg6])
const platAnnouncement = ref('')
const txtForm = ref({
  zoningId: undefined,
  articleText: undefined,
  customerId: undefined,
  articleTitle: undefined,
  articlePicture: undefined
})
const txtRules = ref({
  articleTitle: [{ required: false, message: t('blog.r1'), trigger: 'blur' }],
  zoningId: [{ required: true, message: t('blog.r2'), trigger: 'blur' }],
  articleText: [{ required: true, message: t('blog.r3'), trigger: 'blur' }]
})
const txtFormEl = ref(null)

const reportForm = ref({
  articleId: undefined,
  customerId: undefined,
  reportInfo: undefined,
  reportType: undefined,
  reportScreenshot: undefined
})
const queryForm = ref({
  pageSize: 10,
  pageNum: 1,
  queryType: -1
})
const currentPageIndex = ref(0)
const fileList = ref([])
const upload1 = ref(null)
const upload2 = ref(null)
const setFileList = (val) => {
  fileList.value = val
}
// 上传
const handleUpload = (ref, list) => {
  return new Promise((resolve, reject) => {
    const newList = list.value.filter((item) => item.raw)
    const oldList = list.value.filter((item) => !item.raw).map((item) => item.url)

    if (newList.length) {
      const formData = new FormData()
      newList.forEach((item) => {
        formData.append('files', item.raw)
      })
      uploads(formData).then(({ urls }) => {
        const resultFile = urls.split(',')
        list.value = resultFile.map((item) => {
          return {
            name: item.slice(item.lastIndexOf('/') + 1),
            url: item
          }
        })
        ref.value.setFileList(fileList.value)
        resolve([...oldList, ...resultFile])
      })
    } else {
      resolve(oldList)
    }
  })
}
const changeList = (item) => {
  if (item.id != -1) {
    queryForm.value.queryType = item.id
    getList()
  } else {
    queryForm.value.queryType = -1
    getNoticesListFn()
  }
}
const getNoticesListFn = () => {
  getNoticesList().then((res) => {
    listData.value = res.rows
    platAnnouncement.value = res.total
  })
}
const getList = () => {
  listPage(queryForm.value).then((res) => {
    listData.value = res.rows.map((item) => {
      item.commentFlag = false
      item.shareFLag = false
      item.likeFlag = item.isLike > 0 ? true : false
      item.collectFlag = item.isCollect > 0 ? true : false
      return item
    })
  })
}
const hotList = () => {
  popularList().then((res) => {
    hotListData.value = res.data
  })
}
const nextFn = () => {
  if (currentPageIndex.value == Math.ceil(zoningList.value.length / 6) - 1) {
    return false
  } else {
    currentPageIndex.value = currentPageIndex.value + 1
    tabList.value.style.marginLeft = -(1260 * currentPageIndex.value) + 'px'
  }
}
const preFn = () => {
  if (currentPageIndex.value == 0) {
    return false
  } else {
    currentPageIndex.value = currentPageIndex.value - 1
    tabList.value.style.marginLeft = 1260 * currentPageIndex.value + 'px'
  }
}
const routerPush = (row) => {
  openUrl('/blogDetail', { id: row.id })
}
//点赞||取消点赞
const changeLike = async (value, item) => {
  let data = {
    customerId: JSON.parse(localStorage.getItem('login')).userInfo.id,
    objType: 0,
    objId: item.id
  }
  if (value == 0) {
    item.likeFlag = true
    await articleLike(data).then(({ msg }) => {
      showSuccessToast(msg)
    })
  } else {
    item.likeFlag = false
    await articleCancelLike(data).then(({ msg }) => {
      showSuccessToast(msg)
    })
  }
  // getList()
}
// 收藏|取消收藏
const changeCollect = async (value, item) => {
  let data = {
    customerId: JSON.parse(localStorage.getItem('login')).userInfo.id,
    // objType:0,
    articleId: item.id
  }
  if (value == 0) {
    item.collectFlag = true
    await articleCollect(data).then(({ msg }) => {
      showSuccessToast(msg)
    })
  } else {
    item.collectFlag = false
    await cancelFavorite(data).then(({ msg }) => {
      showSuccessToast(msg)
    })
  }
  // getList()
}
const shareFlagChange = (item, value) => {
  item.shareFLag = value
}
//分享
const shareFn = (type) => {
  if (type == 'link') {
    // navigator.clipboard.writeText(window.location.href)
  } else {
    generateQrCode({ link: window.location.href }).then((res) => {
      currentLinkImg.value = window.URL.createObjectURL(res)
      QrCodeVis.value = true
    })
  }
}
//新增文章
const addArticle = () => {
  if (!txtFormEl.value) return
  txtFormEl.value.validate(async (valid, fields) => {
    if (valid) {
      let urllist = await handleUpload(upload1, fileList)
      if (urllist.length) {
        txtForm.value.articlePicture = urllist.join()
      }
      let data = {
        ...txtForm.value,
        customerId: JSON.parse(localStorage.getItem('login')).userInfo.id
      }
      articleAdd(data).then(({ msg }) => {
        showSuccessToast(msg)
        txtForm.value = {
          zoningId: undefined,
          articleText: undefined,
          customerId: undefined,
          articleTitle: undefined,
          articlePicture: undefined
        }
        diaologVis.value = false
        // getList()
      })
    }
  })
}
const reportFilelist = ref([])
const setReportFilelist = (val) => {
  reportFilelist.value = val
}
// 举报文章
const openReport = (row) => {
  reportForm.value.articleId = row.zoningId
  reportDialog.value = true
}
const reportSub = async () => {
  let res = await handleUpload(upload2, reportFilelist)
  if (res.length) {
    reportForm.value.reportScreenshot = res.join()
  }
  let data = {
    ...reportForm.value,
    customerId: JSON.parse(localStorage.getItem('login')).userInfo.id
  }
  articleReport(data).then(({ msg }) => {
    showSuccessToast(msg)
    reportForm.value = {
      articleId: undefined,
      customerId: undefined,
      reportInfo: undefined,
      reportType: undefined,
      reportScreenshot: undefined
    }
    reportDialog.value = false
    // getList()
  })
}
// 评论列表
const getCurComment = (row) => {
  getCommentList({ articleId: row.id, pageNum: 1, pageSize: 10 }).then((res) => {
    row.commentList = res.rows
    row.commentFlag = true
  })
}
const init = async () => {
  await getDictData('report_type')
  // getList()
  getNoticesListFn()
  hotList()
  getCustomerInfo({ customerId: JSON.parse(localStorage.getItem('login')).userInfo.id }).then((res) => {
    creatorInfo.value = res.data
  })
  getZoningList().then((res) => {
    zoningList.value = res.data
  })
}

onMounted(() => {
  init()
})
</script>

<style scoped lang="scss">
.breadcrumb {
  background: #252628;
  color: #fff;
  padding: 12px 20px;
  font-weight: bold;
}

.user {
  width: 100%;
  padding: 20px 0;
  background: white;
  height: 95px;
  display: flex;
  justify-content: space-between;

  .left {
    display: flex;

    .head-sculpture {
      img {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        margin-right: 12px;
      }
    }

    .name {
      h2 {
        font-size: 16px;

        font-weight: bold;
        color: #252628;
      }

      p {
        font-size: 14px;

        font-weight: 400;
        color: #9d9fa5;
      }
    }
  }

  .right {
    button {
      width: 200px;
      height: 80px;

      font-weight: 400;
      color: #ffffff;
      line-height: 80px;
    }

    :deep(.el-button--primary) {
      span {
        font-size: 14px;
      }
    }
  }
}

.publish-article {
  .input {
    // height: 90px;
  }

  :deep(.el-input__wrapper) {
    border: none;
    background: rgba(245, 245, 245, 1);
    outline: none;
  }

  :deep(.el-textarea__inner) {
    background: rgba(245, 245, 245, 1);
  }

  .sub-box {
    .sub-btn {
      width: 100%;
      height: 50px;
      background: #252628;
      border-radius: 4px;
      font-weight: 400;
      color: #ffffff;
    }
    :deep(.el-button) {
      span {
        font-size: 14px;
      }
    }
  }
}

.user-info {
  display: flex;

  .head-sculpture {
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      margin-right: 12px;
    }
  }

  .name {
    padding-top: 4px;

    h2 {
      font-size: 16px;

      font-weight: bold;
      color: #252628;

      .date {
        font-size: 14px;

        font-weight: 400;
        color: #9d9fa5;
      }
    }

    p {
      font-size: 14px;

      font-weight: 400;
      color: #9d9fa5;
      margin-top: 4px;
    }
  }
}

.partition {
  font-size: 16px;

  font-weight: bold;
  color: #252628;

  span {
    font-size: 26px;
    color: rgba(202, 42, 2, 1);
  }
}

.btn-list {
  width: 100%;
  display: flex;
  margin-bottom: 10px;
  flex-wrap: wrap;

  // justify-content: space-between;
  :deep(.el-button) {
    span {
      font-size: 14px;
    }
  }

  .el-button {
    margin-left: 0px;
    margin-right: 12px;
  }

  button {
    border-radius: 0px;
    background: rgb(250, 198, 185);

    font-weight: 400;
    color: #1c1e22;
    border: none;
    outline: none;
    margin-top: 10px;
    padding: 20px;
  }

  .active {
    background: rgba(202, 42, 2, 1);
    color: white;
  }
}
</style>
